<template>
	<div class="switchButton">
		<div
			v-for="(item,index) in items"
			:key="item.value"
			class="item"
			@click="toggleView(item.value,index)"
		>
			<span :style="{color:index===currentIndex ?activeColor:''}">{{item.label}}</span>
		</div>
		<div
			class="slider"
			:style="sliderStyle"
		/>
	</div>
</template>

<script>
export default {
	props:{
		items:{
			type:Array,
			default:() => [
				{label:'列表', value:'list'},
				{label:'卡片', value:'card'},
			],
		},
		themeColor:{
			type:Object,
			default:() => {},
		},
	},
	data(){
		return {
			active:'list',
			currentIndex:0,
			activeColor:'',
		};
	},
	computed:{
		sliderStyle(){
			const itemWidth = 100 / this.items.length;
			const leftPosition = this.currentIndex === 0
				? '2px'
				: this.currentIndex === this.items.length - 1
					? '-2px'
					: '0px';
			return {
				left:leftPosition,
				transform:`translateX(${this.currentIndex * 100}%)`,
				width:`${itemWidth}%`,
			};
		},
	},
	mounted(){
		this.activeColor = this.themeColor?.color?.primary?.main;
	},
	methods:{
		toggleView(type, index){
			if(type === this.active) return;
			this.active = type;
			this.currentIndex = index;
			this.$emit('change', type);
		},
	},
};
</script>

<style scoped lang="scss">
.switchButton {
	border-radius: 8px;
	background-color: #e7e7e7;
	display: flex;
	align-items: center;
	padding: 4px;
	position: relative;
	width: fit-content;
	height: 32px;
	margin: 0 10px;
	.item {
		cursor: pointer;
		flex: 1;
		text-align: center;
		min-width: 50px;
		box-sizing: border-box;
		position: relative;
		z-index: 1;
		font-size: 14px;
	}
	.slider {
		position: absolute;
		top: 5%;
		width: 50%;
		height: 90%;
		background-color: #ffffff;
		border-radius: 8px;
		transition: transform 0.3s ease;
		z-index: 0;
	}
}
</style>